package vivek.project.pocketmoney.mutualfund.model
{
	import flash.data.*;
	import flash.errors.*;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import mx.collections.ArrayCollection;
	import mx.collections.IViewCursor;
	import mx.collections.ListCollectionView;
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.core.UIComponent;
	import mx.utils.*;
	import vivek.project.pocketmoney.admin.model.*;
	import vivek.project.pocketmoney.common.CommonData;
	import vivek.project.pocketmoney.common.FinancialFormulas;
	import vivek.project.pocketmoney.common.interfaces.RecurssionInterface;
	import vivek.project.pocketmoney.common.logger.PMLogger;
	import vivek.project.pocketmoney.common.utils.ArrayUtils;
	import vivek.project.pocketmoney.common.utils.CommonConstants;
	import vivek.project.pocketmoney.common.utils.DateUtils;
	import vivek.project.pocketmoney.common.utils.StringUtils;
	import vivek.project.pocketmoney.expenses.events.ExpenseEvent;
	import vivek.project.pocketmoney.expenses.model.ExpenseDataModel;
	import vivek.project.pocketmoney.mutualfund.events.MutualFundEvents;
	import vivek.project.pocketmoney.mutualfund.model.utils.MutualFundPriceUpdateWorker;
	import vivek.project.pocketmoney.mutualfund.scripts.*;

	public class MutualFundModel extends UIComponent
	{
		//private  var _sqlConnection : SQLConnection = CommonData.getConnection();
		private static var instance:MutualFundModel;
		private static var MODULE:String="MUTUAL FUND";
		public static function getFundNameById(fundId:int):String
		{
			var accObj:Object=new Object();
			for each (accObj in MutualFundDataCache.mutualFundControl)
			{
				if (accObj.mm_id == fundId)
					return accObj.mm_fundname;
			}
			return "";
		}
		public static function getFundNameForSchemeId(schemeId:int):String
		{
			var scObj:Object=new Object();
			for each (scObj in MutualFundDataCache.schemeControl)
			{
				if (scObj.sm_schemeid == schemeId)
				{
					var fundObj:Object=new Object();
					for each (fundObj in MutualFundDataCache.mutualFundControl)
					{
						if (fundObj.mm_id == scObj.sm_fundid)
							return fundObj.mm_fundname;
					}
				}
			}
			return "";
		}
		public static function getHistoricalNAVListForScheme(schemeId:int):Array
		{
			var _statement:SQLStatement=new SQLStatement();
			var navData:Array=new Array();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			try
			{
				_statement.sqlConnection=connection;
				connection.begin();
				_statement.text=MutualFundScripts.MUTUAL_FUND_NAV_HISTORY_4_SCHEME;
				_statement.parameters[":mfn_schemeid"]=schemeId;
				_statement.execute();
				navData=_statement.getResult().data;
			}
			catch (sqlError:SQLError)
			{
				connection.rollback();
				connection.close();
			}
			_statement=null;
			return navData;
		}
		public static function getInstance():MutualFundModel
		{
			if (!instance)
			{
				/*instance = ExpenseDataModel(
				 Singleton.getInstance("vivek.project.pocketmoney.expenses.model::ExpenseDataModel"));*/
				instance=new MutualFundModel();
			}
			return instance;
		}
		public static function getLatestNAVForScheme(schemeId:int):Number
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			try
			{
				_statement.sqlConnection=connection;
				connection.begin();
				_statement.text=MutualFundScripts.GET_LATEST_NAV_VALUE_FOR_SCHEME;
				_statement.parameters[":mfn_schemeid"]=schemeId;
				_statement.execute();
				var navData:Array=_statement.getResult().data;
				if (navData != null)
					if (navData.length != 0)
						return navData[0].mfn_nav;
				connection.commit();
				connection.close();
			}
			catch (sqlError:SQLError)
			{
				connection.rollback();
				connection.close();
			}
			_statement=null;
			return 0.00;
		}
		public static function getLatestNAVForSchemeMemory(schemeId:int):Number
		{
			var object:Object=new Object();
			for each (object in MutualFundDataCache.schemeControl)
				if (object.sm_schemeid == schemeId)
					return getNAVForSchemeDate(schemeId, object.sm_lastupdated);
			return 0;
		}
		public static function getMFNAVValueOnDate(schemeId:int, navDate:Date):String
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			try
			{
				_statement.sqlConnection=connection;
				connection.begin();
				_statement.text=MutualFundScripts.GET_NAV_VALUE_FOR_DATE;
				_statement.parameters[":mfn_schemeid"]=schemeId;
				_statement.parameters[":mfn_date"]=navDate;
				_statement.execute();
				var navData:Array=_statement.getResult().data;
				if (navData != null)
					if (navData.length != 0)
						return navData[0].mfn_nav;
				connection.commit();
					//connection.close();
			}
			catch (sqlError:SQLError)
			{
				connection.rollback();
				connection.close();
			}
			return "0.00";
		}
		public static function getNAVForSchemeDate(schemeId:int, date:Date):Number
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			try
			{
				_statement.sqlConnection=connection;
				connection.begin();
				_statement.text=MutualFundScripts.MUTUALFUND_SCHEME_NAV_FOR_DATE;
				_statement.parameters[":mfn_schemeid"]=schemeId;
				_statement.parameters[":mfn_date"]=date;
				_statement.execute();
				var navData:Array=_statement.getResult().data;
				if (navData != null)
					if (navData.length != 0)
						return navData[0].mfn_nav;
				connection.commit();
				connection.close();
			}
			catch (sqlError:SQLError)
			{
				connection.rollback();
				connection.close();
			}
			/*			var accObj : Object = new Object();
			   for each ( accObj in MutualFundDataCache.mutualFundNAVHistory)
			   {
			   if (accObj.mfn_schemeid == schemeId && DateUtils.dateCompare(accObj.mfn_date,date)==0)
			   return accObj.mfn_nav;
			   }
			 */
			return 0.00;
		}
		public static function getSchemeForId(schemeId:int):Object
		{
			var accObj:Object=new Object();
			for each (accObj in MutualFundDataCache.schemeControl)
			{
				if (accObj != CommonConstants.SELECT_ONE && accObj.sm_schemeid == schemeId)
					return accObj;
			}
			return accObj;
		}
		public static function getSchemeNameById(schemeId:int):String
		{
			var accObj:Object=new Object();
			accObj=MutualFundDataCache.schemeHash.find(schemeId);
			if (accObj == null)
				return "";
			else
				return accObj.sm_schemename;
		/*for each (accObj in MutualFundDataCache.schemeControl)
		   {
		   if (accObj != CommonConstants.SELECT_ONE && accObj.sm_schemeid == schemeId)
		   return accObj.sm_schemename;
		   }
		 return "";*/
		}
		public static function getTransactionForSchemeId(id:int):Array
		{
			var list:Array=new Array();
			var object:Object=new Object();
			/*for each (object in MutualFundDataCache.mfTransactions)
			   {
			   if (object.mt_schemeid == id)
			   list.push(object);
			 }*/
			var _statement:SQLStatement=new SQLStatement();
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_TRANSACTIONS_4_SCHEME;
			try
			{
				_statement.parameters[":mt_schemeid"]=id;
				_statement.execute();
				list=_statement.getResult().data;
			}
			catch (exception:SQLError)
			{
				return list;
			}
			//	refreshSchemeName(_sqlConnection);
			_sqlConnection.close();
			_sqlConnection=null;
			_statement=null;
			return list;
		}
		public function MutualFundModel()
		{
			runRecurssions();
			loadData();
			AdminDataModel.getInstance().addEventListener("USERCHANGED", loadDataEvent);
			addEventListener(MutualFundEvents.MutualFundCoreChanged, refreshMutualFundCore);
			addEventListener(MutualFundEvents.MutualFundTransactionUpdated, refreshMutualFundTransactionData);
			addEventListener(MutualFundEvents.MutualFundTransactionAdded, refreshMutualFundTransactionData);
			addEventListener(MutualFundEvents.MutualFundTransactionDeleted, refreshMutualFundTransactionData);
			//edm.addEventListener("ExpenseTransactionDeleted", deleteDependentTransaction);
		}
		private function deleteDependentTransaction(event:ExpenseEvent):void
		{
			if (event.data.em_category == CommonConstants.MUTUALFUND_CATEGORY_ID)
			{
				deleteDependentMFTxnId(event.data.em_expenseid);
			}
			trace(event);
		}
		private function deleteDependentMFTxnId(mt_id:int):void
		{
			var _statement:SQLStatement=new SQLStatement();
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			_statement.sqlConnection=_sqlConnection
			_statement.text=MutualFundScripts.MUTUAL_FUND_DELETE_TRANSACTION;
			_statement.parameters[":mt_id"]=mt_id;
			_statement.execute();
			//if(refresh)
			_sqlConnection.close();
			//refreshMutualFundTransactions(connection);
		}
		private var edm:ExpenseDataModel=ExpenseDataModel.getInstance();
		public function addFundName(obj:Object, _sqlConnection:SQLConnection):int
		{
			var _statement:SQLStatement=new SQLStatement();
			try
			{
				_statement.sqlConnection=_sqlConnection;
				_statement.text=MutualFundScripts.MUTUAL_FUND_ADD_FUND;
				_statement.parameters[":mm_fundname"]=obj.mm_fundname;
				_statement.execute();
			}
			catch (error:SQLError)
			{
				return 1;
			}
			dispatchEvent(new Event(MutualFundEvents.MutualFundCoreChanged));
			return 0;
		}
		public function addMFNAVBlockToHistory(valueArray:Array):void
		{
			var _statement:SQLStatement=new SQLStatement();
			var _statement2:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.begin();
			//trace (mfid + "\t " + navValue + "\t"+ navDate);
			//connection.open();
			if (valueArray.length != 0)
			{
				//clearMFNAValue(valueArray[0].mfid);
				_statement.sqlConnection=connection;
				_statement2.sqlConnection=connection;
				for each (var object:Object in valueArray)
				{
					/*_statement.text=MutualFundScripts.DELETE_HISTORICAL_NAV;
					   _statement.parameters[":mfn_schemeid"] = mfid;

					 */
					var year:String=object.navDate.substr(6, 4);
					var month:String=object.navDate.substr(3, 2);
					var date:String=object.navDate.substr(0, 2);
					var conNavDate:Date=new Date(new Number(year), new Number(month) - 1, new Number(date));
					//_statement.parameters[":mfn_date"] = conNavDate;
					//_statement.execute();
					//if (!getMFNAVOnDateExists(object.mfid, conNavDate)){
					if (!connection.inTransaction)
						connection.begin();
					try
					{
						_statement.text=MutualFundScripts.ADD_HISTORICAL_NAV;
						_statement.parameters[":mfn_schemeid"]=object.mfid;
						_statement.parameters[":mfn_date"]=conNavDate;
						_statement.parameters[":mfn_nav"]=object.mfValue;
						_statement.execute();
						trace(object.mfid + "\t" + object.mfValue + "\t" + conNavDate);
					}
					catch (sqlError:Error)
					{
						//if (connection.inTransaction)
						//	connection.rollback();
						trace("ERROR : " + object.mfid + "\t" + object.mfValue + "\t" + conNavDate + ", Could not be ADDED, Reason : " + sqlError.message);
					}
					try
					{
						_statement2.text="update schememanager set sm_lastupdated=:sm_lastupdated where sm_schemeid=:sm_schemeid";
						_statement2.parameters[":sm_schemeid"]=object.mfid;
						_statement2.parameters[":sm_lastupdated"]=conNavDate;
						_statement2.execute();
						trace(object.mfid + "\t" + object.mfValue + "\t" + conNavDate);
						//else
						{
							//	trace(object.mfid + "\t" + object.mfValue + "\t" + conNavDate + "\tRecord Exists");
						}
					}
					catch (sqlError:Error)
					{
						//if (connection.inTransaction)
						//	connection.rollback();
						trace("ERROR : " + object.mfid + "\t" + object.mfValue + "\t" + conNavDate + ", Could not be UPDATED, Reason : " + sqlError.message);
					}
				}
				refreshSchemeName(connection);
				//TODO:				refreshMutualFundNAVHistory(connection);
				if (connection.inTransaction)
					connection.commit();
				connection.close();
			}
		}
		public function addMFNAVValueToDatabase(mfid:int, navValue:String, navDate:String):void
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			try
			{
				_statement.sqlConnection=connection;
				connection.begin();
				_statement.text=MutualFundScripts.UPDATE_MF_NAV;
				_statement.parameters[":sm_schemeid"]=mfid;
				_statement.parameters[":sm_navvalue"]=StringUtils.trimSpecialChar(navValue);
				var year:String="20" + navDate.substr(6, 2);
				var month:String=navDate.substr(3, 2);
				var date:String=navDate.substr(0, 2);
				var conNavDate:Date=new Date(new Number(year), new Number(month) - 1, new Number(date));
				_statement.parameters[":sm_navdate"]=conNavDate;
				_statement.execute();
				refreshSchemeName(connection);
				connection.commit();
				connection.close();
			}
			catch (sqlError:SQLError)
			{
				connection.rollback();
				connection.close();
				trace(mfid + " " + navValue + ", Could not be updated, Reason : " + sqlError.details);
			}
		}
		public function addMFNAVValueToHistory(mfid:int, navValue:String, navDate:String):void
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			trace(mfid + "\t " + navValue + "\t" + navDate);
			//connection.open();
			try
			{
				_statement.sqlConnection=connection;
				connection.begin();
				/*_statement.text=MutualFundScripts.DELETE_HISTORICAL_NAV;
				   _statement.parameters[":mfn_schemeid"] = mfid;

				 */
				var year:String=navDate.substr(6, 4);
				var month:String=navDate.substr(3, 2);
				var date:String=navDate.substr(0, 2);
				var conNavDate:Date=new Date(new Number(year), new Number(month) - 1, new Number(date));
				//_statement.parameters[":mfn_date"] = conNavDate;
				//_statement.execute();
				_statement.text=MutualFundScripts.ADD_HISTORICAL_NAV;
				_statement.parameters[":mfn_schemeid"]=mfid;
				_statement.parameters[":mfn_date"]=conNavDate;
				_statement.parameters[":mfn_nav"]=navValue;
				_statement.execute();
				refreshSchemeName(connection);
				refreshMutualFundNAVHistory(connection);
				connection.commit();
				connection.close();
			}
			catch (sqlError:Error)
			{
				connection.rollback();
				connection.close();
				trace(mfid + " " + navValue + ", Could not be updated, Reason : " + sqlError.message);
			}
		}
		public function addMutualFundRecussion(obj:Object):int
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			_statement.sqlConnection=connection
			_statement.text=MutualFundScripts.MUTUAL_FUND_ADD_RECURSSION;
			_statement.parameters[":mr_status"]=obj.mr_status;
			_statement.parameters[":mr_startdate"]=obj.mr_startdate;
			_statement.parameters[":mr_enddate"]=obj.mr_enddate;
			_statement.parameters[":mr_date"]=obj.mr_date;
			_statement.parameters[":mr_amount"]=obj.mr_amount;
			_statement.parameters[":mr_schemeid"]=obj.mr_schemeid;
			_statement.parameters[":mr_channel"]=obj.mr_channel;
			_statement.parameters[":mr_account"]=obj.mr_account;
			_statement.parameters[":mr_txntype"]=obj.mr_txntype;
			_statement.parameters[":mr_nextexecution"]=RecurssionInterface.getNextExecutionDate(obj.mr_startdate, obj.mr_enddate, obj.mr_date);
			_statement.parameters[":USERID"]=AdminDataCache.ACCOUNT_IN_USE;
			_statement.execute();
			refreshMutualFundRecurssions(connection);
			connection.close();
			return 0;
		}
		public function addMutualFundTransaction(obj:Object, refresh:Boolean):int
		{
			var connection:SQLConnection=CommonData.getConnection();
			try
			{
				connection.begin();
				addMFundTransaction(obj, connection, refresh);
				connection.commit();
				connection.close();
				dispatchEvent(new Event(MutualFundEvents.MutualFundTransactionAdded));
			}
			catch (sqlError:SQLError)
			{
				trace("MF : addMutualFundTransaction : " + sqlError.details);
				connection.rollback();
				connection.close();
				return 9;
			}
			return 0;
		}
		public function addSchemeName(obj:Object, _sqlConnection:SQLConnection):int
		{
			var _statement:SQLStatement=new SQLStatement();
			try
			{
				_statement.sqlConnection=_sqlConnection;
				_statement.text=MutualFundScripts.MUTUAL_FUND_ADD_SCHEME;
				_statement.parameters[":sm_schemeid"]=obj.sm_schemeid;
				_statement.parameters[":sm_schemename"]=obj.sm_schemename;
				_statement.parameters[":sm_schemetype"]=obj.sm_schemetype;
				_statement.parameters[":sm_navdate"]=obj.sm_navdate;
				_statement.parameters[":sm_navvalue"]=obj.sm_navvalue;
				_statement.parameters[":sm_fundid"]=obj.sm_fundid;
				_statement.parameters[":sm_investtype"]=obj.sm_investtype;
				_statement.parameters[":sm_entryLoadPercent"]=obj.sm_entryLoadPercent;
				_statement.parameters[":sm_exitLoadPercent"]=obj.sm_exitLoadPercent;
				_statement.parameters[":sm_exitLoadDays"]=obj.sm_exitLoadDays;
				_statement.execute();
			}
			catch (error:SQLError)
			{
				return 1;
			}
			dispatchEvent(new Event(MutualFundEvents.MutualFundCoreChanged));
			return 0;
		}
		public function clearMFNAValue(mfid:int):void
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			try
			{
				_statement.sqlConnection=connection;
				connection.begin();
				_statement.text="delete from mutualfundnavhistory where mfn_schemeid =:mfn_schemeid";
				_statement.parameters[":mfn_schemeid"]=mfid;
				_statement.execute();
				connection.commit();
				connection.close();
			}
			catch (sqlError:SQLError)
			{
				connection.rollback();
				connection.close();
			}
		}
		public function deleteMFSIP(obj:Object, refresh:Boolean, _sqlConnection:SQLConnection):int
		{
			var _statement:SQLStatement=new SQLStatement();
			try
			{
				_statement.sqlConnection=_sqlConnection;
				_sqlConnection.begin();
				_statement.text=MutualFundScripts.DELETE_FUND_RECURSSIONS;
				_statement.parameters[":mr_id"]=obj.mr_id;
				_statement.execute();
				_sqlConnection.commit();
				PMLogger.log(MODULE, "Mutual Fund SIP DELETED", obj);
			}
			catch (error:SQLError)
			{
				_sqlConnection.rollback();
				return 1;
			}
			if (refresh)
				refreshMutualFundRecurssions(_sqlConnection);
			return 0;
		}
		public function deleteMFTxn(obj:Array, refresh:Boolean=true):int
		{
			var _statement:SQLStatement=new SQLStatement();
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			var mfEditObject:Object=new Object();
			//_sqlConnection.open();
			try
			{
				_statement.sqlConnection=_sqlConnection;
				_sqlConnection.begin();
				_statement.text=MutualFundScripts.MUTUAL_FUND_DELETE_TRANSACTION;
				for each (mfEditObject in obj)
				{
					_statement.parameters[":mt_id"]=mfEditObject.mt_id;
					_statement.execute();
					PMLogger.log(MODULE, "MF transaction DELETED", obj);
					ExpenseDataModel.getInstance().deleteDependentExpense(mfEditObject.mt_id, true, _sqlConnection, mfEditObject);
				}
				_sqlConnection.commit();
				_sqlConnection.close();
				dispatchEvent(new Event(MutualFundEvents.MutualFundTransactionDeleted));
				/*if (refresh)
				   refreshMutualFundTransactions(_sqlConnection);
				   _sqlConnection.commit();
				 _sqlConnection.close();*/
			}
			catch (error:SQLError)
			{
				_sqlConnection.rollback();
				_sqlConnection.close();
				return 1;
			}
			return 0;
		}
		[Event(name="mutualFundCoreChanged")]
		public function deleteSchemeId(id:int):int
		{
			var _statement:SQLStatement=new SQLStatement();
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_DELETE_SCHEME;
			try
			{
				_statement.parameters[":id"]=id;
				_statement.execute();
				PMLogger.log(MODULE, "Mutual Fund scheme DELETED", id);
				dispatchEvent(new Event(MutualFundEvents.MutualFundCoreChanged));
			}
			catch (exception:SQLError)
			{
				return 9;
			}
			//	refreshSchemeName(_sqlConnection);
			_sqlConnection.close();
			return 0;
		}
		public function fillHistoricalData(fromDate:Date, toDate:Date):void
		{
			var startDate:Date=fromDate;
			var mfWorker:MutualFundPriceUpdateWorker=new MutualFundPriceUpdateWorker();
			var newDate:Date=ObjectUtil.copy(startDate) as Date;
			var endDate:Date=toDate;
			while (newDate <= endDate)
			{
				if (newDate.day != 0 && newDate.day != 7)
					for each (var s:Object in MutualFundDataCache.schemeControl)
					{
						if (getNAVForSchemeDate(s.sm_schemeid, newDate) == 0.00)
						{
							var mfpuw:MutualFundPriceUpdateWorker=new MutualFundPriceUpdateWorker();
							mfpuw.getHistoricNAVValue(s.sm_schemeid, newDate.date, newDate.month, newDate.fullYear);
						}
					}
				newDate=DateUtils.dateAdd("date", 1, newDate);
			}
		}
		public function fillHistoricalDataMoneyControl(fromDate:Date, toDate:Date):void
		{
			var startDate:Date=fromDate;
			var mfWorker:MutualFundPriceUpdateWorker=new MutualFundPriceUpdateWorker();
			var newDate:Date=ObjectUtil.copy(startDate) as Date;
			var endDate:Date=toDate;
			while (newDate <= endDate)
			{
				for each (var s:Object in MutualFundDataCache.schemeControl)
				{
					if (getNAVForSchemeDate(s.sm_schemeid, newDate) == 0.00)
					{
						var mfpuw:MutualFundPriceUpdateWorker=new MutualFundPriceUpdateWorker();
						mfpuw.getHistoricNAVValue(s.sm_schemeid, newDate.date, newDate.month, newDate.fullYear);
					}
				}
				newDate=DateUtils.dateAdd("date", 1, newDate);
			}
		}
		public function fillHistoricalDataSingleThread(fromDate:Date, toDate:Date):void
		{
			var startDate:Date=fromDate;
			var mfWorker:MutualFundPriceUpdateWorker=new MutualFundPriceUpdateWorker();
			var newDate:Date=ObjectUtil.copy(startDate) as Date;
			var endDate:Date=toDate;
			while (newDate <= endDate)
			{
				if (newDate.day != 0 && newDate.day != 7)
					for each (var s:Object in MutualFundDataCache.schemeControl)
					{
						//getHistoricNAVValue(s.sm_schemeid,newDate.date,newDate.month+1,newDate.fullYear);
						mfWorker=new MutualFundPriceUpdateWorker();
						mfWorker.getHistoricNAVValue(s.sm_schemeid, newDate.date, newDate.month + 1, newDate.fullYear);
					}
				newDate=DateUtils.dateAdd("date", 1, newDate);
			}
		}
		public function getMFNAVOnDateExists(schemeId:int, date:Date):Boolean
		{
			for each (var obj:Object in MutualFundDataCache.mutualFundNAVHistory)
			{
				if (obj.mfn_schemeid == schemeId)
				{
					//trace (schemeId+"\t"+CommonData.getDateFormatterSlash().format(date)+"\t"+obj.mfn_schemeid +"\t"+CommonData.getDateFormatterSlash().format(obj.mfn_date))
					if (DateUtils.dateCompare(date, obj.mfn_date) == 0)
						return true;
				}
			}
			return false
		}
		public function getMutualFundTransaction(id:int):Object
		{
			var mfObj:Object=new Object();
			for each (mfObj in MutualFundDataCache.mfTransactions)
			{
				if (mfObj.mt_id == id)
					return mfObj;
			}
			return null;
		}
		/*public function loadMFDataFromMYSQL() : void
		   {
		   var sqlFile : File = File.applicationDirectory.resolvePath("vivek/project/pocketmoney/common/mftxndata.csv");
		   if (sqlFile.exists)
		   {
		   var _sqlConnection:SQLConnection = CommonData.getConnection();
		   var _statement : SQLStatement = new SQLStatement();
		   //_sqlConnection.open();
		   var fileStream : FileStream = new FileStream();
		   fileStream.open(sqlFile , FileMode.READ);
		   var fileInfo : String = fileStream.readUTFBytes(fileStream.bytesAvailable);
		   fileStream.close();
		   var parts : Array = fileInfo.split( '\n' );
		   _statement.sqlConnection = _sqlConnection;
		   for( var i : int; i < parts.length; i++)
		   {
		   var dataParts:Array = parts[i].toString().split(',');
		   try
		   {
		   if ( '' != parts[i] )
		   {
		   _statement.text = MutualFundScripts.MUTUAL_FUND_ADD_TRANSACTION;
		   _statement.parameters[":mt_schemeid"]=dataParts[10];
		   _statement.parameters[":mt_nav"]=dataParts[3];
		   _statement.parameters[":mt_unit"]=dataParts[4];
		   _statement.parameters[":mt_channel"]=dataParts[7];
		   _statement.parameters[":mt_txntype"]=dataParts[13];
		   _statement.parameters[":mt_account"]=dataParts.mt_account;
		   _statement.parameters[":mt_memo"]="";
		   _statement.parameters[":mt_folio"]=dataParts[9];
		   if (dataParts[12]=="")
		   {
		   var randomId:Number = Math.round(Math.random() * 1000000000);
		   _statement.parameters[":mt_id"] = randomId;
		   }
		   else
		   {
		   _statement.parameters[":mt_id"] = dataParts[12];}
		   var curDate:Date=new Date(new Number(dataParts[0].substr(0,4)),new Number(dataParts[0].substr(5,2))-1,new Number(dataParts[0].substr(8,2)));
		   _statement.parameters[":mt_date"]=curDate;
		   _statement.execute();
		   }
		   _sqlConnection.close();
		   }

		   catch (error : SQLError)
		   {
		   //Alert.show(error.details);
		   _sqlConnection.close();
		   trace(error.details);
		   //_sqlConnection.close();
		   //return;

		   }
		   }
		   refreshMutualFundTransactions(_sqlConnection);
		   }
		 }*/
		public function refreshMutualFundTransactionsBuy(_sqlConnection:SQLConnection):ArrayCollection
		{
			var _statement:SQLStatement=new SQLStatement();
			trace("MF : refreshMutualFundTransactions : " + new Date().toLocaleTimeString() + ": before refresh");
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_TRANSACTION_BUY;
			//_statement.parameters[":USERID"]=AdminDataCache.ACCOUNT_IN_USE;
			_statement.execute();
			return new ArrayCollection(_statement.getResult().data);
		}
		public function refreshMutualFundTransactionsSell(_sqlConnection:SQLConnection):ArrayCollection
		{
			var _statement:SQLStatement=new SQLStatement();
			trace("MF : refreshMutualFundTransactions : " + new Date().toLocaleTimeString() + ": before refresh");
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_TRANSACTION_SELL;
			//_statement.parameters[":USERID"]=AdminDataCache.ACCOUNT_IN_USE;
			_statement.execute();
			return new ArrayCollection(_statement.getResult().data);
		}
		public function updateFundName(id:int, value:String):int
		{
			var _statement:SQLStatement=new SQLStatement();
			try
			{
				_statement.sqlConnection=CommonData.getConnection();
				_statement.text=MutualFundScripts.MUTUAL_FUND_UPDATE_FUND;
				_statement.parameters[":mm_id"]=id;
				_statement.parameters[":mm_fundname"]=value;
				_statement.execute();
				refreshFundName(CommonData.getConnection());
			}
			catch (error:SQLError)
			{
				return 1;
			}
			//dispatchEvent(new Event(MutualFundEvents.MutualFundCoreChanged));
			return 0;
		}
		public function updateMFField(fieldName:String, value:Object, stockId:Number):void
		{
			var sqlConnection:SQLConnection=CommonData.getConnection();
			var _statement:SQLStatement=new SQLStatement();
			try
			{
				_statement.sqlConnection=sqlConnection;
				var UPDATE_STOCK_RECORD_FIELD:String="UPDATE mutualfundtransaction SET " + fieldName + " = :VALUE WHERE mt_id=:stockId";
				_statement.text=UPDATE_STOCK_RECORD_FIELD;
				//_statement.parameters[":FIELDNAME"]=fieldName;
				_statement.parameters[":VALUE"]=value;
				_statement.parameters[":stockId"]=stockId;
				_statement.execute();
				//refreshExpenseData(sqlConnection);
				sqlConnection.close();
				_statement=null;
				//loadData();
				//edm.refreshExpenseDataCache(null);
				PMLogger.log("MF", "MF update", value);
				dispatchEvent(new Event(MutualFundEvents.MutualFundTransactionUpdated));
			}
			catch (e:Error)
			{
				trace(e.message);
			}
		}
		public function updateMFQtyField(unit:Number, nav:Number, amount:Number, stockId:Number):void
		{
			var sqlConnection:SQLConnection=CommonData.getConnection();
			var _statement:SQLStatement=new SQLStatement();
			try
			{
				_statement.sqlConnection=sqlConnection;
				var UPDATE_STOCK_RECORD_FIELD:String="UPDATE mutualfundtransaction SET my_amountinvested=:amount , mt_nav =:nav,mt_unit=:unit WHERE mt_id=:stockId";
				_statement.text=UPDATE_STOCK_RECORD_FIELD;
				//_statement.parameters[":FIELDNAME"]=fieldName;
				_statement.parameters[":amount"]=amount;
				_statement.parameters[":unit"]=unit;
				_statement.parameters[":nav"]=nav;
				_statement.parameters[":stockId"]=stockId;
				_statement.execute();
				//refreshExpenseData(sqlConnection);
				sqlConnection.close();
				_statement=null;
				edm.updateExpenseField("em_amount", amount, stockId);
				PMLogger.log(MODULE, "Mutual Fund QTY updated", stockId);
				dispatchEvent(new Event(MutualFundEvents.MutualFundTransactionUpdated));
			}
			catch (e:Error)
			{
				trace(e.message);
			}
		}
		public function updateMutualFundNextExecutionDate(obj:Object, connection:SQLConnection, date:Date, refresh:Boolean):void
		{
			trace(new Date().toLocaleTimeString() + "MR: start add 1");
			var _statement:SQLStatement=new SQLStatement();
			_statement.sqlConnection=connection;
			_statement.text="update mutualfundrecurssion set mr_nextexecution = :nextExecutionDate, mr_lastexecution=:lastExecutedDate where mr_id = :mr_id";
			_statement.parameters[":nextExecutionDate"]=obj.nextExecutionDate;
			_statement.parameters[":lastExecutedDate"]=obj.lastExecutedDate;
			_statement.parameters[":mr_id"]=obj.mt_id;
			_statement.execute();
			refreshMutualFundRecurssions(connection);
		}
		public function updateMutualFundRecussion(obj:Object):int
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			_statement.sqlConnection=connection
			_statement.text=MutualFundScripts.MUTUAL_FUND_UPDATE_RECURSSION;
			_statement.parameters[":mr_status"]=obj.mr_status;
			_statement.parameters[":mr_startdate"]=obj.mr_startdate;
			_statement.parameters[":mr_enddate"]=obj.mr_enddate;
			_statement.parameters[":mr_date"]=obj.mr_date;
			_statement.parameters[":mr_amount"]=obj.mr_amount;
			_statement.parameters[":mr_schemeid"]=obj.mr_schemeid;
			_statement.parameters[":mr_channel"]=obj.mr_channel;
			_statement.parameters[":mr_account"]=obj.mr_account;
			_statement.parameters[":mr_txntype"]=obj.mr_txntype;
			_statement.parameters[":mr_nextexecution"]=RecurssionInterface.getNextExecutionDate(obj.mr_startdate, obj.mr_enddate, obj.mr_date);
			_statement.parameters[":mr_id"]=obj.mr_id;
			_statement.execute();
			refreshMutualFundRecurssions(connection);
			connection.close();
			return 0;
		}
		public function updateMutualFundTransaction(id:int, obj:Object, refresh:Boolean):void
		{
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			try
			{
				connection.begin();
				//trace(new Date().toLocaleTimeString() + "MF: start add 1");
				deleteMFTxnId(id, connection, false, obj);
				//trace(new Date().toLocaleTimeString() + "MF: start add 2");
				addMFundTransaction(obj, connection, true);
				connection.commit();
				connection.close();
				dispatchEvent(new Event(MutualFundEvents.MutualFundTransactionUpdated));
			}
			catch (sqlError:SQLError)
			{
				trace(new Date().toLocaleTimeString() + "ERROR Occured :" + sqlError.message);
				connection.rollback();
				connection.close();
			}
			//trace(new Date().toLocaleTimeString() + "MF: start add 3");
		}
		public function updatePortfolioType(mfid:int, giantCap:String, largeCap:String, midCap:String, smallCap:String, tinyCap:String):void
		{
			var _statement:SQLStatement=new SQLStatement();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			try
			{
				_statement.sqlConnection=connection;
				connection.begin();
				_statement.text=MutualFundScripts.UPDATE_MF_CAPDATA;
				_statement.parameters[":sm_schemeid"]=mfid;
				_statement.parameters[":sm_giantcap"]=StringUtils.trimSpecialChar(giantCap);
				_statement.parameters[":sm_largecap"]=StringUtils.trimSpecialChar(largeCap);
				_statement.parameters[":sm_midcap"]=StringUtils.trimSpecialChar(midCap);
				_statement.parameters[":sm_smallcap"]=StringUtils.trimSpecialChar(smallCap);
				_statement.parameters[":sm_tinycap"]=StringUtils.trimSpecialChar(tinyCap);
				_statement.execute();
				refreshSchemeName(connection);
				connection.commit();
				connection.close();
				dispatchEvent(new Event("MutualFundDistributionChanged"));
			}
			catch (sqlError:SQLError)
			{
				connection.rollback();
				connection.close();
				trace(mfid + "," + giantCap + "," + largeCap + "," + midCap + "," + smallCap + "," + tinyCap + "," + sqlError.message);
			}
		}
		public function updateScheme(obj:Object, _sqlConnection:SQLConnection):int
		{
			var _statement:SQLStatement=new SQLStatement();
			var _statement2:SQLStatement=new SQLStatement();
			try
			{
				_statement.sqlConnection=_sqlConnection;
				_sqlConnection.begin();
				_statement.text=MutualFundScripts.MUTUAL_FUND_SCHEME_UPDATE;
				_statement.parameters[":sm_schemeid"]=obj.sm_schemeid;
				_statement.parameters[":sm_id"]=obj.sm_id;
				_statement.parameters[":sm_schemename"]=obj.sm_schemename;
				_statement.parameters[":sm_schemetype"]=obj.sm_schemetype;
				//_statement.parameters[":sm_navdate"]=obj.sm_navdate;
				//	_statement.parameters[":sm_navvalue"]=obj.sm_navvalue;
				_statement.parameters[":sm_fundid"]=obj.sm_fundid;
				_statement.parameters[":sm_investtype"]=obj.sm_investtype;
				_statement.parameters[":sm_entryLoadPercent"]=obj.sm_entryLoadPercent;
				_statement.parameters[":sm_exitLoadPercent"]=obj.sm_exitLoadPercent;
				_statement.parameters[":sm_exitLoadDays"]=obj.sm_exitLoadDays;
				_statement.execute();
				_statement2.sqlConnection=_sqlConnection;
				_statement2.text=MutualFundScripts.MUTUAL_FUND_TRANSACTION_SCHEME_UPDATE;
				_statement2.parameters[":mt_schemeid"]=obj.sm_schemeid;
				_statement2.execute();
				_sqlConnection.commit();
				_sqlConnection.close();
			}
			catch (error:SQLError)
			{
				_sqlConnection.rollback();
				_sqlConnection.close();
				return 1;
			}
			dispatchEvent(new Event(MutualFundEvents.MutualFundCoreChanged));
			return 0;
		}
		private function addMFundTransaction(obj:Object, connection:SQLConnection, refresh:Boolean):void
		{
			trace(new Date().toLocaleTimeString() + "MF: start add");
			var _statement:SQLStatement=new SQLStatement();
			_statement.sqlConnection=connection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_ADD_TRANSACTION;
			_statement.parameters[":mt_date"]=obj.mt_date;
			_statement.parameters[":mt_schemeid"]=obj.mt_schemeid;
			_statement.parameters[":mt_nav"]=obj.mt_nav;
			_statement.parameters[":mt_unit"]=(obj.mt_amount / obj.mt_nav);
			_statement.parameters[":mt_channel"]=obj.mt_channel;
			_statement.parameters[":mt_txntype"]=obj.mt_txntype;
			_statement.parameters[":mt_account"]=obj.mt_account;
			_statement.parameters[":mt_memo"]=obj.mt_memo;
			_statement.parameters[":mt_folio"]=obj.mt_folio;
			_statement.parameters[":my_amountinvested"]=obj.mt_amount;
			_statement.parameters[":USERID"]=obj.mt_userid;
			var randomId:Number=new Number();
			randomId=Math.round(Math.random() * 1000000000);
			_statement.parameters[":mt_id"]=randomId;
			_statement.execute();
			trace(new Date().toLocaleTimeString() + "MF:start add- step 1 done ");
			var expRecord:Object=new Object();
			expRecord.account=obj.mt_account;
			if (obj.mt_txntype == MutualFundConstants.BUY)
			{
				expRecord.type=CommonConstants.WITHDRAWAL;
			}
			else
			{
				expRecord.type=CommonConstants.DEPOSIT;
			}
			expRecord.amount=obj.mt_amount;
			expRecord.category=CommonConstants.MUTUALFUND_CATEGORY_ID;
			expRecord.payee=0;
			expRecord.memo=obj.mt_memo;
			expRecord.date=obj.mt_date;
			expRecord.exRate=1.0;
			expRecord.account=obj.mt_account
			expRecord.userid=obj.mt_userid;
			if (expRecord.account != 0)
				edm.addDependentExpenseRecord(expRecord, randomId, connection);
		/* if (refresh)
		   {
		   //MutualFundDataCache.mfTransactions = new ArrayCollection( _statement.getResult().data);
		   refreshMutualFundTransactions(connection);
		 } */
		}
		private function calculateAvailable():void
		{
			var object:Object=new Object();
			//for each (object in MutualFundDataCache.mutualFundAvailable)
			{
				//trace(object.mt_schemeid + "\t"+object.mt_unit + "\t"+object.mt_available);
				//	if (object.mt_available!=0)
				//	MutualFundDataCache.mutualFundAvailable.addItem(object);
			}
		}
		private function calculateBuySell():void
		{
			trace("MF : calculate buy sell  :\t " + new Date().toTimeString() + " \t:  Started");
			var buyArray:Array=new Array();
			var finalArray:Array=new Array();
			var sellArray:ArrayCollection=new ArrayCollection();
			var mfList:ListCollectionView=new ListCollectionView(MutualFundDataCache.mfTransactions);
			sellArray.disableAutoUpdate();
			MutualFundDataCache.currentHoldingValue=0;
			//	buyArray.disableAutoUpdate();						
			var sort:Sort=new Sort();
			sort.fields=[new SortField("mt_channel", false), new SortField("mt_schemeid", false), new SortField("mt_date", false)];
			mfList.sort=sort;
			mfList.refresh();
			var object:Object=new Object();
			var tempObject:Object=new Object();
			for each (object in mfList)
			{
				tempObject=new Object();
				tempObject.mt_available=object.mt_unit;
				tempObject.mt_channel=object.mt_channel;
				tempObject.mt_schemeid=object.mt_schemeid;
				tempObject.sm_schemename=object.sm_schemename;
				tempObject.mt_amount=object.mt_amount;
				tempObject.mt_unit=object.mt_unit;
				tempObject.mt_nav=object.mt_nav;
				tempObject.mt_date=object.mt_date;
				tempObject.sm_schemetype=object.sm_schemetype;
				tempObject.sm_investtype=object.sm_investtype;
				tempObject.sellunit=0;
				tempObject.sellnav=0;
				tempObject.selldate=0;
				tempObject.mt_sellamount=0;
				tempObject.mt_daysSell=DateUtils.dateDiff(new Date(), tempObject.mt_date);
				tempObject.mt_currentvalue=Math.round(tempObject.mt_available * MutualFundDataCache.hash.find(tempObject.mt_schemeid) * 100) / 100;
				tempObject.mt_profit=tempObject.mt_currentvalue - tempObject.mt_amount;
				tempObject.mt_cagrReturn=0; //FinancialFormulas.calculateCAGR(tempObject.mt_amount, tempObject.mt_currentvalue, tempObject.sellamount, tempObject.mt_daysSell / 365);
				tempObject.mt_absReturn=0; //ancialFormulas.calculateAbsReturns(tempObject.mt_amount, tempObject.mt_currentvalue, tempObject.sellamount, tempObject.mt_daysSell / 12);
				tempObject.mt_anReturn=0; //FinancialFormulas.calculateAnnualizedReturn(tempObject.mt_amount, tempObject.mt_currentvalue, tempObject.sellamount, tempObject.mt_daysSell);
//				tempObject.mt_dString=object.mt_date.toDateString();
				if (object.mt_txntype == MutualFundConstants.BUY)
				{
					buyArray.push(tempObject);
				}
				else
				{
					sellArray.addItem(tempObject);
				}
			}
			var buySort:Sort=new Sort();
			buySort.fields=[new SortField("mt_channel", false), new SortField("mt_schemeid", false)];
			//buyArray.sort=buySort;
			//buyArray.refresh();
			var sellSort:Sort=new Sort();
			sellSort.fields=[new SortField("mt_channel", false), new SortField("mt_schemeid", false)];
			//sellArray.sort=sellSort;
			//sellArray.refresh();
			//var buyCursor:IViewCursor=sellArray.createCursor();
			var sellCursor:IViewCursor=sellArray.createCursor();
			var sellObject:Object=new Object();
			var buyObject:Object=new Object();
			var matchArray:Array=new Array();
			while (!sellCursor.afterLast)
			{
				sellObject=sellCursor.current;
				//	if (sellObject.mt_schemeid==695)
				{
					matchArray=ArrayUtils.findMatchingItem(sellObject, buyArray, ['mt_channel', 'mt_schemeid']);
					if (matchArray.length != 0)
					{
						buyObject=matchArray[0];
						if (buyObject.mt_available != 0)
						{
							if (buyObject.mt_available == sellObject.mt_available)
							{
								buyObject.sm_schemename=sellObject.sm_schemename;
								buyObject.sellunit=sellObject.mt_available;
								buyObject.sellnav=sellObject.mt_nav;
								buyObject.selldate=sellObject.mt_date;
								buyObject.mt_available=0;
								buyObject.mt_sellamount=(buyObject.sellnav * buyObject.sellunit);
								buyObject.mt_profit=buyObject.mt_sellamount - buyObject.mt_amount;
								sellObject.mt_available=0;
								finalArray.push(buyObject);
								buyObject.mt_currentvalue=0;
								buyObject.mt_daysSell=DateUtils.dateDiff(sellObject.mt_date, buyObject.mt_date);
								buyObject.mt_cagrReturn=FinancialFormulas.calculateCAGR(buyObject.mt_amount, buyObject.mt_currentvalue, buyObject.mt_sellamount, buyObject.mt_daysSell / 365);
								buyObject.mt_absReturn=FinancialFormulas.calculateAbsReturns(buyObject.mt_amount, buyObject.mt_currentvalue, buyObject.mt_sellamount, buyObject.mt_daysSell / 30);
								buyObject.mt_anReturn=FinancialFormulas.calculateAnnualizedReturn(buyObject.mt_amount, buyObject.mt_currentvalue, buyObject.sellamount, buyObject.mt_daysSell);
								//buyCursor.remove();
								buyArray.splice(buyArray.indexOf(buyObject), 1);
									//trace(buyObject.mt_schemeid + "\t"+buyObject.mt_unit + "\t"+buyObject.mt_available+"\t"+buyObject.mt_profit);						
							}
							else
							{
								if (sellObject.mt_available > buyObject.mt_available)
								{
									buyObject.sellunit=buyObject.mt_available;
									buyObject.sellnav=sellObject.mt_nav;
									buyObject.selldate=sellObject.mt_date;
									sellObject.mt_available=sellObject.mt_available - buyObject.mt_available;
									buyObject.mt_available=0;
									buyObject.mt_sellamount=(buyObject.sellnav * buyObject.sellunit);
									buyObject.mt_profit=buyObject.mt_sellamount - buyObject.mt_amount;
									finalArray.push(buyObject);
									sellObject.mt_currentvalue=(sellObject.mt_available * MutualFundDataCache.hash.find(tempObject.mt_schemeid));
									buyObject.mt_currentvalue=0;
									buyObject.mt_daysSell=DateUtils.dateDiff(sellObject.mt_date, buyObject.mt_date);
									buyObject.mt_cagrReturn=FinancialFormulas.calculateCAGR(buyObject.mt_amount, buyObject.mt_currentvalue, buyObject.mt_sellamount, buyObject.mt_daysSell / 365);
									buyObject.mt_absReturn=FinancialFormulas.calculateAbsReturns(buyObject.mt_amount, buyObject.mt_currentvalue, buyObject.mt_sellamount, buyObject.mt_daysSell / 30);
									buyObject.mt_anReturn=FinancialFormulas.calculateAnnualizedReturn(buyObject.mt_amount, buyObject.mt_currentvalue, buyObject.sellamount, buyObject.mt_daysSell);
									var i:int=buyArray.indexOf(buyObject);
									buyArray.splice(i, 1);
									sellCursor.movePrevious();
										//trace(buyObject.mt_schemeid + "\t"+buyObject.mt_unit + "\t"+buyObject.mt_available+"\t"+buyObject.mt_profit);
								}
								else
								{
									var partSellObject:Object=new Object();
									partSellObject=ObjectUtil.copy(buyObject);
									partSellObject.sellunit=sellObject.mt_available;
									partSellObject.sellnav=sellObject.mt_nav;
									partSellObject.selldate=sellObject.mt_date;
									buyObject.mt_available=buyObject.mt_available - sellObject.mt_available;
									buyObject.mt_amount=buyObject.mt_available * buyObject.mt_nav;
									buyObject.mt_unit=buyObject.mt_available;
									buyObject.mt_currentvalue=buyObject.mt_available * MutualFundDataCache.hash.find(tempObject.mt_schemeid);
									partSellObject.mt_sellamount=partSellObject.sellnav * partSellObject.sellunit;
									partSellObject.mt_profit=partSellObject.mt_sellamount - (partSellObject.sellunit * partSellObject.mt_nav);
									partSellObject.mt_available=0;
									partSellObject.mt_currentvalue=0;
									partSellObject.mt_unit=sellObject.mt_unit;
									partSellObject.mt_amount=partSellObject.sellunit * partSellObject.mt_nav;
									sellObject.mt_available=0;
									buyObject.mt_profit=buyObject.mt_currentvalue - buyObject.mt_amount;
									partSellObject.mt_daysSell=DateUtils.dateDiff(partSellObject.mt_date, partSellObject.mt_date);
									if (partSellObject.mt_daysSell > 365)
										partSellObject.mt_cagrReturn=FinancialFormulas.calculateCAGR(partSellObject.mt_amount, partSellObject.mt_currentvalue, buyObject.mt_sellamount, partSellObject.mt_daysSell / 365);
									else
										buyObject.mt_cagrReturn=FinancialFormulas.calculateAbsReturns(partSellObject.mt_amount, partSellObject.mt_currentvalue, buyObject.mt_sellamount, partSellObject.mt_daysSell / 30);
									finalArray.push(partSellObject);
										//trace(partSellObject.mt_schemeid + "\tsell unit"+partSellObject.mt_unit + "\tavailable"+partSellObject.mt_available+ "\tProfit"+partSellObject.mt_profit+"\tPartSell");
								}
							}
						}
					}
					else
					{
						//	buyCursor.
					}
				}
				sellCursor.moveNext();
			}
			for each (var temp:Object in buyArray)
			{
				temp.mt_cagrReturn=FinancialFormulas.calculateCAGR(temp.mt_amount, temp.mt_currentvalue, temp.sellamount, temp.mt_daysSell / 365);
				temp.mt_absReturn=FinancialFormulas.calculateAbsReturns(temp.mt_amount, temp.mt_currentvalue, temp.sellamount, temp.mt_daysSell / 12);
				temp.mt_anReturn=FinancialFormulas.calculateAnnualizedReturn(temp.mt_amount, temp.mt_currentvalue, temp.sellamount, temp.mt_daysSell);
				//	trace(temp.mt_currentvalue + "\t" + MutualFundDataCache.currentHoldingValue);
				MutualFundDataCache.currentHoldingValue+=temp.mt_currentvalue;
			}
			MutualFundDataCache.mutualFundBuySell.source=finalArray;
			MutualFundDataCache.mutualFundAvailable.source=buyArray;
			sellArray=null;
			mfList=null
			matchArray=null;
			trace("MF : calculate buy sell  :\t " + new Date().toTimeString() + " \t:  Ended");
//		for each (object in buyArray)
//			trace(object.mt_schemeid + "\t"+object.mt_unit + "\t"+object.mt_available);
		}
		private function convertToMutualFundTransaction(array:Array):Array
		{
			var arrayColl:Array=new Array();
			trace("MF : convertToMutualFund : \t" + new Date().toTimeString() + " : Before Refresh");
			if (array == null)
				return arrayColl;
			for (var i:int; i < array.length; i++)
			{
				var a2:MutualFundTransactionScript=new MutualFundTransactionScript();
				a2.mt_schemeid=array[i].mt_schemeid;
				a2.mt_unit=array[i].mt_unit;
				a2.mt_nav=array[i].mt_nav;
				a2.mt_date=array[i].mt_date;
				a2.mt_channel=array[i].mt_channel;
				a2.mt_id=array[i].mt_id;
				a2.mt_account=array[i].mt_account;
				a2.mt_txntype=array[i].mt_txntype;
				a2.mt_amount=array[i].my_amountinvested;
				a2.sm_investtype=array[i].sm_investtype;
				a2.sm_schemetype=array[i].sm_schemetype;
				a2.mt_folio=array[i].mt_folio;
				a2.sm_fundid=array[i].sm_fundid;
				arrayColl.push(a2);
			}
			trace("MF : convertToMutualFund : \t" + new Date().toTimeString() + " : " + "After Refresh");
			return arrayColl;
		}
		private function deleteMFTxnId(mt_id:int, connection:SQLConnection, refresh:Boolean, obj:Object):void
		{
			var _statement:SQLStatement=new SQLStatement();
			_statement.sqlConnection=connection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_DELETE_TRANSACTION;
			_statement.parameters[":mt_id"]=mt_id;
			_statement.execute();
			ExpenseDataModel.getInstance().deleteDependentExpense(mt_id, false, connection, obj);
			PMLogger.log(MODULE, "Mutual Fund Transaction DELETED", obj);
			//if(refresh)
			//refreshMutualFundTransactions(connection);
		}
		private function doHistoricalEvent(evt:Event):void
		{
			switch (evt.type)
			{
				case Event.COMPLETE: /* If the load was successful, create a URLVariables object from the URLLoader.data property and populate the paramColl ArrayCollection object. */
					var ldr:URLLoader=evt.currentTarget as URLLoader;
					var urlData:String=ldr.data;
					var value:String=StringUtils.stripBetweenNOccurance(urlData, "<br>Entry Price (Rs.) :", 1, "<form>");
					value=StringUtils.trimSpecialChar(value);
					trace(value);
					//mutualFundModel.addMFNAVValueToHistory(mfid,value,CommonData.dateFormatter.format(histDate));
					break;
				case IOErrorEvent.IO_ERROR:
				{
					dispatchEvent(new Event("UpdateCompletedWithError"));
					break;
				}
			}
		}
		private function getHistoricNAVValue(schemeid:int, day:int=1, month:int=1, year:int=2009):void
		{
			var url:String="http://valueresearchonline.com/port/getentryprice.asp?schemecode=1386&day=6&month=3&year=2008&amount=10000&units=";
			var textLoader:URLLoader=new URLLoader();
			var textReq:URLRequest=new URLRequest(url);
			textReq.method=URLRequestMethod.POST;
			var variables:URLVariables=new URLVariables();
			variables.schemecod=schemeid;
			variables.day=day;
			variables.month=month;
			variables.year=year;
			variables.amount="10000";
			variables.amount=""
			var histDate:Date=new Date(year, month, day);
			textReq.data=variables;
			textLoader.load(textReq);
			textLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doHistoricalEvent);
			textLoader.addEventListener(IOErrorEvent.IO_ERROR, doHistoricalEvent);
			textLoader.addEventListener(Event.COMPLETE, doHistoricalEvent);
		}
		private function loadData():void
		{
			var conn:SQLConnection=CommonData.getConnection();
			//conn.open();
			refreshFundName(conn);
			refreshSchemeName(conn);
			refreshMutualFundTransactions(conn);
			refreshMutualFundRecurssions(conn);
			refreshMutualFundNAVHistory(conn);
			calculateBuySell();
			//calculateAvailable();
			conn.close();
		}
		private function loadDataEvent(event:Event):void
		{
			loadTransactionalData();
			//flash.system.System.gc();
			//flash.system.System.gc();
		}
		private function loadTransactionalData():void
		{
			var conn:SQLConnection=CommonData.getConnection();
			//conn.open();
			refreshMutualFundTransactions(conn);
			refreshMutualFundRecurssions(conn);
			calculateBuySell();
			//calculateAvailable();
			conn.close();
			dispatchEvent(new Event(MutualFundEvents.MutualFundCachedRefreshed));
		}
		private function refreshFundName(_sqlConnection:SQLConnection):void
		{
			var _statement:SQLStatement=new SQLStatement();
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_CONTROL;
			_statement.execute();
			MutualFundDataCache.mutualFundControl.source=_statement.getResult().data;
		}
		private function refreshMutualFundCore(event:Event):void
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			refreshFundName(_sqlConnection);
			refreshSchemeName(_sqlConnection);
			refreshMutualFundTransactions(_sqlConnection);
			//calculateBuySell();
			_sqlConnection.close();
			dispatchEvent(new Event(MutualFundEvents.MutualFundCachedRefreshed));
		}
		private function refreshMutualFundNAVHistory(_sqlConnection:SQLConnection):void
		{
			//trace("MF : refreshMutualFundHistory\t:Start:\t"+new Date().toTimeString());
			var _statement:SQLStatement=new SQLStatement();
			_statement.sqlConnection=_sqlConnection;
			//_statement.text=MutualFundScripts.MUTUAL_FUND_NAV_HISTORY;
			//_statement.execute();
			//MutualFundDataCache.mutualFundNAVHistory.source=_statement.getResult().data;
			_statement.text=MutualFundScripts.GET_LATEST_NAV_VALUE_FOR_SCHEME;
			_statement.execute();
			MutualFundDataCache.hash.clear();
			var object:Object=new Object();
			for each (object in _statement.getResult().data)
			{
				MutualFundDataCache.hash.insert(object.mfn_schemeid, object.mfn_nav);
			}
			//trace("MF : refreshMutualFundHistory \t:End:\t"+new Date().toTimeString());
		}
		private function refreshMutualFundRecurssions(_sqlConnection:SQLConnection):void
		{
			//trace("MF : refreshMutualFundRecurssion \t:Start:\t"+new Date().toTimeString());
			var _statement:SQLStatement=new SQLStatement();
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_RECURSSIONS;
			//_statement.parameters[":USERID"]=AdminDataCache.ACCOUNT_IN_USE;
			_statement.execute();
			MutualFundDataCache.mutualFundRecurssions.source=_statement.getResult().data;
			//trace("MF : refreshMutualFundRecurssion \t:End:\t"+new Date().toTimeString());
		}
		private function refreshMutualFundTransactionData(event:Event):void
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			refreshMutualFundTransactions(_sqlConnection);
			calculateBuySell();
			_sqlConnection.close();
			//edm.refreshExpenseDataCache(null);
			dispatchEvent(new Event(MutualFundEvents.MutualFundCachedRefreshed));
		}
		private function runRecurssions():void
		{
			var _statement:SQLStatement=new SQLStatement();
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_RECURSSIONS_ALL;
			_statement.execute();
			var recussions:ArrayCollection=new ArrayCollection();
			recussions.source=_statement.getResult().data;
			var currentDate:Date=new Date();
			var obj:Object=new Object();
			var connection:SQLConnection=CommonData.getConnection();
			//connection.open();
			//trace(new Date().toTimeString()+"\tMutualFundModule:runRecurssions\tStart");
			for each (obj in recussions)
			{
				var startDate:Date=obj.mr_startdate;
				var endDate:Date=obj.mr_enddate;
				var amount:Number=obj.mr_amount;
				var type:int=obj.mr_txntype;
				var onDate:int=obj.mr_date;
				var category:int=11;
				var memo:String=obj.mr_schemeid;
				var lastExecutedDate:Date=obj.mr_lastexecution;
				var fromAccount:int=obj.mr_account;
				var channel:int=obj.mr_channel;
				var nextExecutionDate:Date=obj.mr_nextexecution;
				var rmId:int=obj.mr_id;
				var schemeid:int=obj.mr_schemeid;
				var todayDate:Date=new Date();
				var i:int=0;
				var dateCompare:int=DateUtils.dateCompare(nextExecutionDate, todayDate);
				if ((dateCompare == 0 || dateCompare == 1) && obj.mr_status == 1)
				{
					var nextDate:Date=nextExecutionDate; //RecurssionInterface.getNextExecutionDate(startDate,endDate,onDate);
					var toDate:Date=endDate;
					/*	||(ObjectUtil.dateCompare(nextDate,todayDate)==0)
					 ) && (ObjectUtil.dateCompare(nextDate,toDate)==1)*/
					while ((DateUtils.dateCompare(nextDate, todayDate) == 1) || (DateUtils.dateCompare(nextDate, todayDate) == 0))
					{
						var obj1:Object=new Object();
						connection.begin();
						obj1.mt_date=nextDate;
						obj1.mt_schemeid=schemeid;
						obj1.mt_nav=10.00;
						obj1.mt_unit=amount / obj1.mt_unit;
						obj1.mt_amount=amount;
						obj1.mt_txntype=type;
						obj1.mt_account=fromAccount;
						obj1.mt_channel=channel;
						obj1.mt_id=rmId;
						obj1.mt_userid=obj.mr_userid;
						//obj.mt_memo=memo.text;
						obj1.mt_folio="";
						obj1.memo=memo;
						//TODO : if the transaction are more this would slow down hte respnse as expense and mf data would get reloaded everytime
						addMutualFundTransaction(obj1, true);
						obj1.lastExecutedDate=nextDate;
						nextDate=DateUtils.dateAdd("month", 1, nextDate);
						obj1.nextExecutionDate=nextDate;
						updateMutualFundNextExecutionDate(obj1, connection, nextDate, true);
						i++;
						connection.commit();
					}
						//TODO:
				}
			}
			connection.close();
			//trace(new Date().toTimeString()+"\tMutualFundModule:runRecurssions\tEnd");
		}
		private function refreshMutualFundTransactions(_sqlConnection:SQLConnection):void
		{
			var _statement:SQLStatement=new SQLStatement();
			trace("MF : refreshMutualFundTransactions : " + new Date().toLocaleTimeString() + ": before refresh");
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_TRANSACTION_ALL;
			//_statement.parameters[":USERID"]=AdminDataCache.ACCOUNT_IN_USE;
			_statement.execute();
			MutualFundDataCache.mfTransactions.source=new Array();
			//MutualFundDataCache.mfTransactions.source=convertToMutualFundTransaction(_statement.getResult().data);
			MutualFundDataCache.mfTransactions.source=_statement.getResult().data;
			trace("MF : refreshMutualFundTransactions : " + new Date().toLocaleTimeString() + ": after refresh");
		}
		private function refreshSchemeName(_sqlConnection:SQLConnection):void
		{
			var _statement:SQLStatement=new SQLStatement();
			_statement.sqlConnection=_sqlConnection;
			_statement.text=MutualFundScripts.MUTUAL_FUND_SCHEME_ALL;
			_statement.execute();
			MutualFundDataCache.schemeControl.source=_statement.getResult().data;
			var object:Object=new Object();
			MutualFundDataCache.schemeHash.clear();
			for each (object in MutualFundDataCache.schemeControl)
			{
				MutualFundDataCache.schemeHash.insert(object.sm_schemeid, object);
			}
		}
	}
}